<?php

require_once('inc/constants.php');
require_once('inc/out.php');

class AdminBootstrap extends Zend_Application_Bootstrap_Bootstrap
{

	/**
	 * @var Zend_Config
	 */
	private $_config;

	/**
	 * @return void
	 */
	public function _initSetIncludePaths()
	{
		$configurations = require(WSB_APP_PATH . 'inc/config.php');
		$paths = array();
		if(!empty($configurations['includePaths']['zend'])) {
			$paths[] = $configurations['includePaths']['zend'];
		}
		$paths[] = WSB_PATH;
		$paths[] = WSB_APP_PATH . 'library';
		$paths[] = WSB_APP_PATH . 'library/PEAR';
		set_include_path(implode(PATH_SEPARATOR, $paths));
	}

	public function _initMagicQuotesGPCworkaround()
	{
		// Es gibt zur Zeit Probleme mit magic_quotes_gpc=On
		if ((function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc())
		   || (ini_get('magic_quotes_sybase') && (strtolower(ini_get('magic_quotes_sybase'))!="off")) )
		{
			self::stripslashes($_GET);
			self::stripslashes($_POST);
			self::stripslashes($_COOKIE);
			self::stripslashes($_REQUEST);
		}
	}

	public function _initSetHeader()
	{
		header('Content-Type: text/html; charset=utf-8');
	}

	public function _initSetAutoloader()
	{
		require_once 'Zend/Loader/Autoloader.php';
		$autoloader = Zend_Loader_Autoloader::getInstance();
		$autoloader->registerNamespace('WSB_');
		$autoloader->suppressNotFoundWarnings(true);
		$autoloader->setFallbackAutoloader(true);

		// Klassendatei Cache
		$classFileIncCache = WSB_APP_PATH.  'tmp/cache/pluginLoaderCache.php';
		if (file_exists($classFileIncCache)) {
			include_once $classFileIncCache;
		}
		Zend_Loader_PluginLoader::setIncludeFileCache($classFileIncCache);

		// Allgemein benötigte Klassen inkludieren
		require_once(WSB_MODULES_PATH . 'member/models/DbTable/Beuser.php');
		require_once(WSB_MODULES_PATH . 'member/models/DbTable/Feuser.php');
	}

	public function _initTestZendFrameworkVersion()
	{
		if(Zend_Version::compareVersion(WSB_ZEND_FRAMEWORK_VERSION) == -1) {
			// die(sprintf('Zend Framework Version %s ben&ouml;tigt.', Zend_Version::VERSION));
		}
		if(Zend_Version::compareVersion(WSB_ZEND_FRAMEWORK_VERSION) == 1) {
			throw new Exception(sprintf('Zend Framework ab Version %s ben&ouml;tigt.', WSB_ZEND_FRAMEWORK_VERSION));
		}
	}

	public function _initConfig()
	{
		$configPath = 'WSB/inc/config.php';
		$configArray = require($configPath);
		$this->_config = new Zend_Config($configArray);
		Zend_Registry::set('Zend_Config', $this->_config);
	}

	public function _initSession()
	{
		// Initialisiere Session Handling
		$sessionSavePath = WSB_APP_PATH . 'tmp/session';
		if(!is_dir($sessionSavePath)) {
			die(sprintf("Error: Missing folder '%s'.", $sessionSavePath));
		}
		if(!is_writeable($sessionSavePath)) {
			die(sprintf("Error: Folder '%s' is not writable.", $sessionSavePath));
		}

		Zend_Session::setOptions(array('save_path' => $sessionSavePath));
		Zend_Session::start();
	}

	public function _initDb()
	{
		$db = Zend_Db::factory($this->_config->database);
		Zend_Db_Table_Abstract::setDefaultAdapter($db);
		if($this->_config->application->profiler) {
			$db->getProfiler()->setEnabled(true);
		}
		// Using a Default Metadata Cache for all Table Objects
		if($this->_config->database->useMetadataCache) {
			$frontendOptions = array('automatic_serialization' => true);
			$backendOptions  = array('cache_dir' => WSB_APP_PATH . 'tmp/cache');
			$cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
			Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
		}
	}

	public function _initFrontController()
	{
		$request = new Zend_Controller_Request_Http();
		$request->setBaseUrl(WSB_ADMIN_URL);

		$this->frontController = Zend_Controller_Front::getInstance();
		$this->frontController->setParam('useModules', true);
		$this->frontController->setRequest($request);
		//$this->frontController->returnResponse(false);
		//$this->frontController->setParam('noViewRenderer', true);
		//$this->frontController->setParam('noErrorHandler', true);

		//$this->frontController->registerPlugin(new WSB_Controller_Plugin_Initialize());

		$this->frontController->registerPlugin(new WSB_Controller_Plugin_Navigation());
		$this->frontController->registerPlugin(new WSB_Controller_Plugin_Permission());
		$this->frontController->registerPlugin(new WSB_Controller_Plugin_Messenger());
		if($this->_config->application->debug) {
			$this->frontController->registerPlugin(new WSB_Controller_Plugin_Debugger());
		}
		if($this->_config->application->profiler) {
			$this->frontController->registerPlugin(new WSB_Controller_Plugin_Profiler());
		}

		// Helferpfad bekanntmachen
		Zend_Controller_Action_HelperBroker::addPath(WSB_APP_PATH . 'library/WSB/Controller/Helper', 'WSB_Controller_Helper');

		$this->_setControllerDirectories();

		// Fehlerhandling
		//$this->frontController->throwExceptions(false);
		return $this->frontController;
	}

	public function _initLocale()
	{
		require_once(WSB_MODULES_PATH . 'cms/models/DbTable/Language.php');
		$locale = new Zend_Locale(Cms_Model_DbTable_Language::getAdminLanguage());
		Zend_Registry::set('Zend_Locale', $locale);
	}

	public function _initTranslate()
	{
		$translate = new Zend_Translate('csv', WSB_APP_PATH.'i18n', null, array('disableNotices' => true, 'scan' => Zend_Translate::LOCALE_FILENAME));
		Zend_Registry::set('Zend_Translate', $translate);
	}

	public function _initView()
	{
		$options = array(
			'layout' => 'default',
		    'layoutPath' => WSB_APP_PATH . 'design/default/layout/'
		);
		$layout = Zend_Layout::startMvc($options);

		// View Settings
		$view = $layout->getView();
		$view->doctype('XHTML1_TRANSITIONAL');
		$view->addScriptPath(WSB_APP_PATH . 'library/WSB/Controller/views');
		$view->addHelperPath(WSB_APP_PATH . 'library/WSB/View/Helper/', 'WSB_View_Helper');
		//$view->addHelperPath('View/Helper/', 'View_Helper');

		// Head title
		$view->headTitle('WSB Administration');
		$view->headTitle()->setSeparator(' | ');
		$view->headMeta()->appendHttpEquiv('Content-Type', 'text/html; charset=utf-8');

		// Yahoo! UI Library: Container (SimpleDialog)
    	$javascripts = array(
			// @see: http://developer.yahoo.com/yui/articles/hosting/?button&container
			'http://yui.yahooapis.com/combo?2.7.0/build/yahoo-dom-event/yahoo-dom-event.js&2.7.0/build/element/element-min.js&2.7.0/build/button/button-min.js&2.7.0/build/container/container-min.js'
    	);
    	foreach($javascripts AS $src) {
    		$view->headScript()->offsetSetFile($src, $src);
    	}
    	$stylesheets = array(
			// @see: http://developer.yahoo.com/yui/articles/hosting/?button&container
			'http://yui.yahooapis.com/combo?2.7.0/build/button/assets/skins/sam/button.css&2.7.0/build/container/assets/skins/sam/container.css'
    	);
    	foreach($stylesheets AS $link) {
    		$view->headLink()->offsetSetStylesheet($link, $link);
    	}

		// Zend_Dojo_View_Helper_Dojo::setUseDeclarative();
		// $view->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');

		// Template
		$request = new Zend_Controller_Request_Http();
		switch($request->getQuery('TEMPLATE')) {
		    case 'popup':
				$layout->setLayout('popup');
		        break;
		    default:
		        break;
		}

	}

	/*
	public function _initModules()
	{
        $modules = $this->frontController->getControllerDirectory();
        foreach ($modules as $module => $dir) {
            if ('default' == $module) {
                continue;
            }
            $bootstrapFile = dirname($dir) . '/Bootstrap.php';
			if(is_file($bootstrapFile)) {
	            $class = ucfirst($module) . '_Bootstrap';
	            if (Zend_Loader::loadFile('Bootstrap.php', dirname($dir))
	                && class_exists($class)
	            ) {
	                $bootstrap = new $class;
	                $bootstrap->setAppBootstrap($this);
	                $bootstrap->bootstrap();
	            }
			}
        }
	}
	*/


	/**
	 * Setze die Controller Verzeichnisse der Module und installierten Xtmodule
	 *
	 */
	private function _setControllerDirectories()
	{

		// @todo: Nutzung von addModuleDirectory. Bedingung dafuer ist allerdings,
		// dass die, Modulverzeichnisse kleingeschrieben sind.
		/*
        $this->frontController->setControllerDirectory(WSB_APP_PATH . 'Module', 'default');
        $this->frontController->addModuleDirectory(WSB_APP_PATH . 'Module');
		*/

		// Backend modules
		$directories = array(
			'default'		=> WSB_MODULES_PATH
		);
		// Frontend modules
		require_once(WSB_MODULES_PATH . 'cms/models/DbTable/Xtension.php');
		$table = new Cms_Model_DbTable_Xtension();
		$select = $table->select();
		$select->where('deleted=?', 0);
		foreach($table->fetchAll($select) AS $item) {
			$moduleName = $item->getModuleName();
			if(!array_key_exists($moduleName, $directories)) {
				$directories[$moduleName] = $item->getControllerDirectory();
			}
		}

		// Verzeichnisse dem Frontcontroller bekanntmachen
		$this->frontController->setControllerDirectory($directories);

		// Neues Modul- und XTension-Verzeichnis
		// Es ist vorgesehen, dass alle Module des alten Modulverzeichnisses
		// in dieses neue Modulverzeichnis verschoben werden.
        $this->frontController->addModuleDirectory(WSB_MODULES_PATH);
	}

	/**
	 * @param mixed $value
	 * @return mixed
	 */
	public static function stripslashes(&$value)
	{
	    $value = is_array($value) ?
	                array_map(array('AdminBootstrap', 'stripslashes'), $value) :
	                stripslashes($value);
	    return $value;
	}

}